package com.zk.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zk.entity.User;
import com.zk.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
 * <p>
 *  属性自动注入
 * </p>
 *Shiro 认证与授权
 * @author jyx
 * @since 2020-11-30
 */

public class UserRealm extends AuthorizingRealm {
    @Autowired
    @Qualifier("userServiceImpl")
    IUserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //authorization 授权
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        Subject subject= SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        info.addStringPermission(user.getUserRole().toString());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       UsernamePasswordToken token =  (UsernamePasswordToken)authenticationToken;
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        String username = token.getUsername();
        queryWrapper.eq("user_phone",username);

        User currentuser = userService.getOne(queryWrapper);
        if(currentuser==null)
        {
            return null;

        }
        else {

            return new SimpleAuthenticationInfo(username,currentuser.getUserPwd(), ByteSource.Util.bytes(currentuser.getSalt()),getName());
            /*这里的SimpleAuthenticationInfo 三个参数
             *第一个为  用户名principle
             *第二个为  服务器密码
             * 第三个为authenticationInfo的名字getname（）
             * **/
        }


    }
}
